package com.jack.lib;

import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

/**
 * author : chong.huang
 * create : 2022/3/1
 * desc   :
 */
public class SimpleServer extends WebSocketServer {

    public SimpleServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conn.send("发送测试数据"); //This method sends a message to the new client
        broadcast( "发送广播数据" + handshake.getResourceDescriptor() ); //This method sends a message to all clients connected
        Log.e("test", "new connection to " + conn.getRemoteSocketAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        Log.e("test", "closed " + conn.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        Log.e("test", "received message from "	+ conn.getRemoteSocketAddress() + ": " + message);
    }

    @Override
    public void onMessage(WebSocket conn, ByteBuffer message ) {
        Log.e("test", "received ByteBuffer from "	+ conn.getRemoteSocketAddress());
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        String address = conn == null ? "null" : conn.getRemoteSocketAddress() == null ? "null" : conn.getRemoteSocketAddress().toString();
        Log.e("test", "an error occurred on connection " + address  + ":" + ex);
    }

    @Override
    public void onStart() {
        Log.e("test", "server started successfully");
    }


    public static class Data {
        int type;
        String sn;
        String param;
    }
}
